package com.demo.boss.server.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.boss.common.constants.type.SysException;
import com.demo.boss.common.enums.PublicStatus;
import com.demo.boss.common.enums.SysCode;
import com.demo.boss.common.mail.MailProperty;
import com.demo.boss.entity.UserInfo;
import com.demo.boss.entity.UserPayConfig;
import com.demo.boss.entity.UserPayInfo;
import com.demo.boss.mapper.UserInfoMapper;
import com.demo.boss.mapper.UserPayConfigMapper;
import com.demo.boss.mapper.UserPayInfoMapper;
import com.demo.boss.models.PageRequest;
import com.demo.boss.models.dto.MerchPaymentConfigDto;
import com.demo.boss.models.request.UserProductConfigRequest;
import com.demo.boss.server.UserPaymentConfigService;
import com.demo.boss.tools.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.Buffer;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserPaymentConfigServiceImpl implements UserPaymentConfigService {
    @Resource
    private UserPayConfigMapper userPayConfigMapper;
    @Resource
    private UserPayInfoMapper payInfoMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private MailUtil mailUtil;

    @Override
    public IPage<UserPayConfig> pageConfigList(PageRequest pageRequest) {
        Integer pageNo = pageRequest.getPageNo();
        Integer pageSize = pageRequest.getPageSize();
        QueryWrapper<UserPayConfig> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("user_no", "product_code");

        return userPayConfigMapper.selectPage(Page.of(pageNo, pageSize), wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createConfig(UserProductConfigRequest configRequest) {
        log.info("createConfig线程：{}",Thread.currentThread().getName());
        // user_pay_config 表的user_no 和 product_code 二者唯一
        QueryWrapper<UserPayConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("user_no", configRequest.getUserNo())
                .eq("product_code", configRequest.getProductCode());
        Long count = userPayConfigMapper.selectCount(wrapper);
        if (count > 0) {
            throw new SysException(SysCode.PAYMENT_USER_PRODUCT_CONFIG_EXISTS_ERROR);
        }
        StringBuffer buffer = new StringBuffer();
        UserPayConfig userPayConfig = new UserPayConfig();
        userPayConfig.setId(IdWorker.get32UUID());
        userPayConfig.setUserNo(configRequest.getUserNo());
        userPayConfig.setShopName(configRequest.getShopName());
        userPayConfig.setProductCode(configRequest.getProductCode());
        userPayConfig.setProductName(configRequest.getProductName());
        userPayConfig.setRiskDay(configRequest.getRiskDay());
        userPayConfig.setAppKey(IdWorker.get32UUID());
        userPayConfig.setAppSecret(IdWorker.get32UUID());
        userPayConfig.setMerchantServerIp(configRequest.getIpList());
        userPayConfig.setAutoSett("autoYes".equals(configRequest.getAutoSett()) ? "YES" : "NO");
        userPayConfig.setRemark("创建商户配置支付产品");
        userPayConfig.setEditTime(new Date());
        userPayConfig.setStatus(PublicStatus.ENABLE.name());
        userPayConfigMapper.insert(userPayConfig);

        UserProductConfigRequest.KqConfig kqConfig = configRequest.getKqConfig();
        if (kqConfig != null) {
            String jsonStr = JSONUtil.toJsonStr(kqConfig);
            UserPayInfo userPayInfo = new UserPayInfo();
            userPayInfo.setId(IdWorker.get32UUID());
            userPayInfo.setProductCode(configRequest.getProductCode());
            userPayInfo.setUserNo(configRequest.getUserNo());
            userPayInfo.setShopName(configRequest.getShopName());
            userPayInfo.setPayWayCode("KUAIQIAN");
            userPayInfo.setPayWayName("快钱");
            userPayInfo.setPayConfig(jsonStr);
            userPayInfo.setRemark("创建快钱第三方支付参数");
            userPayInfo.setEditTime(new Date());
            userPayInfo.setStatus(PublicStatus.ENABLE.name());
            payInfoMapper.insert(userPayInfo);
            buffer.append("支付方式：KUAIQIAN").append(";");
        }
        UserProductConfigRequest.WxConfig wxConfig = configRequest.getWxConfig();
        if (wxConfig != null) {
            String toJsonStr = JSONUtil.toJsonStr(wxConfig);
            UserPayInfo userPayInfo = new UserPayInfo();
            userPayInfo.setId(IdWorker.get32UUID());
            userPayInfo.setProductCode(configRequest.getProductCode());
            userPayInfo.setUserNo(configRequest.getUserNo());
            userPayInfo.setShopName(configRequest.getShopName());
            userPayInfo.setPayWayCode("WEIXIN");
            userPayInfo.setPayWayName("微信");
            userPayInfo.setPayConfig(toJsonStr);
            userPayInfo.setRemark("创建快钱第三方支付参数");
            userPayInfo.setEditTime(new Date());
            userPayInfo.setStatus(PublicStatus.ENABLE.name());
            payInfoMapper.insert(userPayInfo);
            buffer.append("支付方式：WEIXIN").append(";");
        }
        buffer.append("商户号：").append(configRequest.getUserNo()).append(";")
                .append("支付产品代码：").append(configRequest.getProductCode()).append(";")
                .append("支付产品名称：").append(configRequest.getProductName()).append(";")
                .append("appKey：").append(userPayConfig.getAppKey()).append(";")
                .append("appSecret：").append(userPayConfig.getAppSecret()).append(";");
        // 发送邮件
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_no", configRequest.getUserNo()));
        MerchPaymentConfigDto dto = new MerchPaymentConfigDto();
        dto.setUserMail(userInfo.getUserEmail());
        dto.setSubject("商户支付产品消息 Tip");
        dto.setText(buffer.toString());
        // 自己手动创建另一个线程
        new Thread(()->{
            sendMerchPaymentConfig(dto);
        }).start();

    }

//    @Async  // 开启异步
    public void sendMerchPaymentConfig(MerchPaymentConfigDto dto) {
        MailProperty prop = new MailProperty();
        prop.setFrom("18166059583@163.com");
        prop.setTo(new String[]{dto.getUserMail()});
        prop.setSubject(dto.getSubject());
        prop.setText(dto.getText());
        log.info("邮件信息{}",prop);
        mailUtil.sendSimpleMail(prop);
        log.info("sendMerchPaymentConfig线程：{}",Thread.currentThread().getName());
    }


    @Override
    public List<UserPayInfo> queryPayInfo(String userNo, String productCode) {
        QueryWrapper<UserPayInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_no", userNo)
                .eq("product_code", productCode)
                .orderByAsc("pay_way_code");

        return payInfoMapper.selectList(wrapper);
    }
}
